﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YiLe.BLL.Service;
using YiLe.Model.Domain;

namespace YiLe.View.Roles
{
    public partial class RoleSaveForm : Form
    {
        private IRoleService roleService;
        private IPermissionService permissionService;
        private RoleListForm parentForm;

        public RoleSaveForm(Spring.Context.IApplicationContext ctx, RoleListForm roleListForm)
        {
            InitializeComponent();

            roleService = ctx["RoleService"] as IRoleService;
            permissionService = ctx["PermissionService"] as IPermissionService;
            this.parentForm = roleListForm;
        }

        public RoleSaveForm(Spring.Context.IApplicationContext ctx, RoleListForm roleListForm, Role role):this(ctx, roleListForm)
        {
            //InitializeComponent();
            //roleService = ctx["RoleService"] as IRoleService;
            //permissionService = ctx["PermissionService"] as IPermissionService;
            //this.parentForm = roleListForm;

            this.tbRoleID.Text = role.RoleID.ToString();
            this.tbRoleName.Text = role.RoleName.ToString();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ValidateForm())
            {
                Role role = ParseFormToRole();

                if (this.tbRoleID.Text.Equals("0"))
                {
                    roleService.Save(role);
                }
                else
                {
                    roleService.Update(role);
                }
                this.parentForm.RoleListForm_Load(sender, e);
                this.Close();
            }
        }

        /// <summary>
        /// 验证页面
        /// </summary>
        /// <returns></returns>
        /// <summary>
        /// 验证Form
        /// </summary>
        /// <returns></returns>
        private bool ValidateForm()
        {
            epRoleSave.Clear();
            if (this.tbRoleName.Text.Length == 0)
            {
                epRoleSave.SetError(this.tbRoleName, "登录名不能为空！");
                return false;
            }
            else
            {
                if (!checkIsSelected())
                {
                    MessageBox.Show("请选择菜单模块");
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 将Form中的输入框转换为Role对象和Permission对象
        /// </summary>
        private Role ParseFormToRole()
        {
            int roleID = Int32.Parse(this.tbRoleID.Text.Trim());
            string roleName = this.tbRoleName.Text.Trim();
            //填装Permission的列表
            IList<Permission> pmList = new List<Permission>();
            foreach (Control c in Controls)
            {
                if (c is CheckBox)
                {
                    if ((c as CheckBox).Checked == true)
                    {
                        //查询数据库中的Permission，将其添加到List中，然后保存到Role
                        Permission permission = permissionService.Get(Int32.Parse(c.Name));
                        pmList.Add(permission);
                    }
                }
            }
            Role role = new Role() { RoleID = roleID, RoleName = roleName, Permissions = pmList };
            return role;
        }

        /// <summary>
        /// 判断是否选择了checkbox
        /// </summary>
        /// <param name="isChecked"></param>
        /// <returns></returns>
        private bool checkIsSelected()
        {
            bool isChecked = false;
            foreach (Control c in Controls)
            {
                if (c is CheckBox)
                {
                    if ((c as CheckBox).Checked == true)
                    {
                        isChecked = true;
                        break;
                    }
                }
            }
            return isChecked;
        }

        /// <summary>
        /// 读取权限列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RoleSaveForm_Load(object sender, EventArgs e)
        {
            IList<Permission> permissionList = permissionService.GetAll();//所有的权限列表

            int top = gbPermissionList.Top;
            int left = gbPermissionList.Left;
            for (int i = 0; i < permissionList.Count; i++)
            {
                CheckBox cb = new CheckBox();
                //Model.Domain.Menu menu = MenuList.ElementAt(i);
                //cb.Name = menu.MenuID.ToString();//checkbox的ID号为对应的menuID
                //cb.Text = menu.MenuName;
                //cb.Parent = gbPermissionList;
                Permission permission = permissionList.ElementAt(i);
                cb.Name = permission.PermissionID.ToString();//checkbox的ID号为对应的menuID
                cb.Text = permission.PermissionName;
                if (i % 4 == 0)
                {
                    left = gbPermissionList.Left;
                    top += cb.Height;
                }
                else
                {
                    left = gbPermissionList.Left + i % 4 * cb.Width;
                }
                cb.Top = top;
                cb.Left = left;
                cb.Parent = this;
            }

            if (!this.tbRoleID.Text.Trim().Equals("0"))
            {
                int roleID = Int32.Parse(this.tbRoleID.Text.Trim());
                Role role = roleService.Get(roleID);//利用nhibernate的延迟加载
                IList<Permission> rolePermissionList = role.Permissions;//角色对应的权限列表 

                foreach (Control c in Controls)
                {
                    if (c is CheckBox)
                    {
                        foreach (Permission p in rolePermissionList)
                        {
                            if ((c as CheckBox).Name.Equals(p.PermissionID.ToString()))
                            {
                                //MessageBox.Show((c as CheckBox).Name);
                                (c as CheckBox).Checked = true;
                            }
                        }
                    }
                }
            }
        }
    }
}
